import { ref, onMounted, onUnmounted, nextTick } from "vue";
import { debounce } from "lodash";

/**
 * TODO:目前非通用功能，只适配操作说明功能
 * TODO:可以结合弹窗，封装通用HOOK
 */

export function useElementPosition() {
  const instructionsVisible = ref(false);
  const instructionsLeft = ref("0px");
  const instructionsTop = ref("40px");
  const arrowLeft = ref("0px");
  const arrowTop = ref("40px");
  const instructionsWidth = ref(400);
  let proxyInstance = null;
  let initialInstructionsWidth;

  const handelShowInstructions = async proxy => {
    proxyInstance = proxy;
    instructionsVisible.value = true;
    await nextTick();
    const instructionsTitleEl = proxy.$refs.instructionsTitle;
    const instructionsTitleRect = instructionsTitleEl.getBoundingClientRect();
    instructionsLeft.value = `${instructionsTitleRect.left - instructionsWidth.value - 40}px`;
    instructionsTop.value = `${instructionsTitleRect.top}px`;
    arrowLeft.value = `${instructionsTitleRect.left - 41}px`;
    arrowTop.value = `${instructionsTitleRect.top + 10}px`;
  };

  const handelCloseInstructions = () => {
    window.removeEventListener("resize", handleResize);
    instructionsVisible.value = false;
  };

  const handleResize = debounce(() => {
    if (!proxyInstance?.$refs) return;
    const instructionsTitleEl = proxyInstance.$refs.instructionsTitle;
    if (!instructionsTitleEl) return;
    const instructionsTitleRect = instructionsTitleEl.getBoundingClientRect();
    if (!initialInstructionsWidth) {
      initialInstructionsWidth = instructionsWidth.value;
    }
    instructionsLeft.value = `${instructionsTitleRect.left - initialInstructionsWidth - 40}px`;
    instructionsTop.value = `${instructionsTitleRect.top}px`;
    arrowLeft.value = `${instructionsTitleRect.left - 41}px`;
    arrowTop.value = `${instructionsTitleRect.top + 10}px`;
  }, 10);

  onMounted(() => {
    window.addEventListener("resize", handleResize);
  });

  onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
  });

  return {
    instructionsVisible,
    instructionsLeft,
    instructionsTop,
    arrowLeft,
    arrowTop,
    instructionsWidth,
    handelShowInstructions,
    handelCloseInstructions,
    handleResize
  };
}
